"use strict";
import * as React from 'react';
const { View, TextInput, Keyboard, CameraRoll, TouchableOpacity, FlatList, Image, ActivityIndicator } = require('react-native');
const { connect } = require('react-redux');
const NavigationBar = require('react-native-navbar').default;
import { autoSize, commonProps, commonStyles } from "../../assets/styles/common";
import NavBackButton from "../../component/BackButton";
import { postingsInputProps, postingsStyles } from "../../assets/styles/community";
import { NAVBAR_HEIFHT, SCREEN_HEIGHT, SCREEN_WIDTH } from "../../constant";
import MyIcon from "../../component/icon";
import MyText from "../../component/MyText";
import MyGallery from "../../component/MyGallery";
import Colors from "../../assets/styles/Colors";
import { toastValidateError } from "../../utils/tools";
import T from "../../utils/T";
import constant from "../../utils/constant";
const ImageCompress = require('react-native-wtfssd-imagecompress').default;
class NewPostingsPage extends React.Component {
    constructor(props, context) {
        super(props, context);
        this._keyboardDidShow = (props) => {
            const { height, screenY } = props.endCoordinates;
            this.setState({ height: SCREEN_HEIGHT - height - NAVBAR_HEIFHT - autoSize(40) + 14 });
        };
        this._keyboardDidHide = (props) => {
            const { height, screenY } = props.endCoordinates;
        };
        this.chooseImage = (isShowCameraRoll) => {
            this.setState({ isShowCameraRoll });
            if (isShowCameraRoll && this._input.isFocused()) {
                Keyboard.dismiss();
            }
            if (!isShowCameraRoll && !this._input.isFocused()) {
                this._input.focus();
            }
        };
        this.selectedImage = (selectedImage) => {
            this.chooseImage(false);
            this.setState({ selectedImage: { progress: true } });
            ImageCompress.compress(selectedImage.image.uri, constant.maxUpLoadImageSize).then(e => {
                console.log('压缩结果', e);
                this.setState({ selectedImage: Object.assign({}, e, { progress: false }) });
            }).catch(e => {
                toastValidateError(null, e.message);
                this.setState({ selectedImage: null });
            });
        };
        this.selectedFromCamera = () => {
            this.chooseImage(false);
        };
        this.deleteSelectedImage = () => {
            this.setState({ selectedImage: null });
        };
        this.onChangeText = (content) => {
            this.setState({ content });
        };
        this.onSubmit = () => {
            let flag = false;
            if (flag)
                return;
            if (this.getCanSubmit()) {
                Keyboard.dismiss();
                let payload = {
                    type: this.props.postType,
                    item: this.props.item
                };
                payload['content'] = this.state.content;
                if (this.state.selectedImage) {
                    payload['image'] = {
                        uri: this.state.selectedImage.data,
                        type: 'application/octet-stream',
                        name: this.state.selectedImage.fileName
                    };
                }
                this.props.dispatch({
                    type: 'post/newPost',
                    payload
                });
            }
        };
        this.getCanSubmit = () => {
            return !!this.state.content;
        };
        this.renderItem = ({ item, index }) => {
            if (index === 0) {
                return (<TouchableOpacity style={[commonStyles.centerVH, Object.assign({}, this._itemSize)]} activeOpacity={1} onPress={this.selectedFromCamera.bind(this)}>
                    <MyIcon name='icon-icon-camera-copy' color='#DAC229' size={40}/>
                </TouchableOpacity>);
            }
            return (<TouchableOpacity style={[commonStyles.centerVH, Object.assign({}, this._itemSize)]} activeOpacity={1} onPress={this.selectedImage.bind(this, item.node)}>
                <Image source={{ uri: item.node.image.uri }} style={{ width: SCREEN_WIDTH / 3, height: SCREEN_WIDTH / 3 }}/>
            </TouchableOpacity>);
        };
        this.renderToolBar = () => {
            const { isShowCameraRoll } = this.state;
            if (isShowCameraRoll) {
                return (<View style={[commonStyles.flexRow, postingsStyles.toolBar, commonStyles.relative, { justifyContent: 'center' }]}>
                    <TouchableOpacity onPress={this.chooseImage.bind(this, false)} style={[commonStyles.flexRow, { position: 'absolute', left: 10 }]}>
                        <MyText style={{ marginLeft: 10, color: '#DAC229' }}>取消</MyText>
                    </TouchableOpacity>
                    <MyText style={{ color: '#333', }}>相机胶卷</MyText>
                </View>);
            }
            return (<View style={[commonStyles.flexRow, postingsStyles.toolBar]}>
                <TouchableOpacity onPress={this.chooseImage.bind(this, true)} style={[commonStyles.flexRow, { alignItems: 'center' }]}>
                    <MyIcon name='icon-addpicture' color='#999999'/>
                    <MyText style={{ marginLeft: 10, color: '#999999' }}>添加图片</MyText>
                </TouchableOpacity>
            </View>);
        };
        this.renderSelectedImage = () => {
            if (!this.state.selectedImage)
                return null;
            return (<View style={[postingsStyles.selectedImageContainer, this.state.selectedImage.progress ? commonStyles.centerVH : null]}>

                {this.state.selectedImage.progress ? <ActivityIndicator color={Colors.Active}/> :
                <View style={[commonStyles.flex1, commonStyles.relative]}>
                        <TouchableOpacity style={[postingsStyles.selectedImageDelete, commonStyles.centerVH]} onPress={this.deleteSelectedImage}>
                            <MyIcon name='icon-cha1' color='#fff' size={10}/>
                        </TouchableOpacity>
                        <Image source={{ uri: this.state.selectedImage.data }} style={postingsStyles.selectedImage}/>
                    </View>}
            </View>);
        };
        this.renderLoadingView = () => {
            if (!this.props.post.loading)
                return null;
            return (<View style={[commonStyles.absolute, commonStyles.centerVH, { left: 0, top: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT, zIndex: 1, backgroundColor: 'rgba(0,0,0,0.5)' }]}>
                <ActivityIndicator color={Colors.Active} size={'large'}/>
                <MyText color={Colors.Active}>{T('loading')}</MyText>
            </View>);
        };
        this.state = {
            height: SCREEN_HEIGHT,
            isShowCameraRoll: false,
            selectedImage: null,
            content: null
        };
        this._itemSize = { width: SCREEN_WIDTH / 3, height: SCREEN_WIDTH / 3 };
    }
    componentWillMount() {
        this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
        this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
    }
    componentWillUnmount() {
        this.keyboardDidShowListener.remove();
        this.keyboardDidHideListener.remove();
    }
    render() {
        return (<View style={[commonStyles.container, commonStyles.relative, { backgroundColor: '#fff' }]}>
                <NavigationBar {...commonProps.navBar} leftButton={<NavBackButton icon={{ name: 'icon-cha1', color: '#999999', size: 25 }}/>} rightButton={{
            title: '提交',
            tintColor: this.getCanSubmit() ? Colors.Active : '#666',
            handler: this.onSubmit
        }} title={{ title: '新帖子', tintColor: '#fff' }}/>
                <View style={[{ height: this.state.height }]}>
                    <View style={[commonStyles.relative, commonStyles.flex1, postingsStyles.inputContainer]}>
                        <TextInput {...postingsInputProps} placeholder={this.props.tip} onChangeText={this.onChangeText} onBlur={this.chooseImage.bind(this, true)} onFocus={this.chooseImage.bind(this, false)} ref={(input) => {
            this._input = input;
        }}/>
                        {this.renderSelectedImage()}
                    </View>

                    {this.renderToolBar()}
                </View>
                {this.state.isShowCameraRoll ?
            <MyGallery style={[commonStyles.flex1]} onSelectedImage={this.selectedImage}/> : null}

                {this.renderLoadingView()}
            </View>);
    }
}
NewPostingsPage.defaultProps = {
    tip: '你现在在想什么?'
};
export default connect(({ auth, post }) => ({ auth, post }))(NewPostingsPage);
